<?php View::display('technic/menu');?>
<?php $products = $params['products'];?>
<link href="css/smoothness/jquery-ui-1.10.3.custom.css" rel="stylesheet">
<script src="js/jquery-ui-1.10.3.custom.js"></script>
<!-- .head -->
<header class="head">
	<!-- ."main-bar -->
	<div class="main-bar">
		<div class="container-fluid">
			<div class="row-fluid">
				<div class="span12">
					<h3>
						<i class="icon-wrench"></i> บริการของลูกค้า
					</h3>
				</div>
			</div>
			<!-- /.row-fluid -->
		</div>
		<!-- /.container-fluid -->
	</div>
	<!-- /.main-bar -->
</header>
<!-- /.head -->
<!-- #content -->
<div id="content">
	<!-- .outer -->
	<div class="container-fluid outer">
	
		<div class="row-fluid">
			<!-- .inner -->
			<div class="span12 inner">
				<!--Begin Datatables-->
				<div class="row-fluid">
					<div class="span12">
						<div class="box">
							<header>
								<div style="padding: 10px;">
									<button class="btn btn-success addColoButton">Add Colo</button>
									<button class="btn btn-success addVPSButton">Add VPS</button>
									<button class="btn btn-success addHostingButton">Add Hosting</button>
								</div>
							</header>
							<div class="body">
								<table class="table table-bordered dataTable responsive">
									<thead>
										<tr>
											<th>id</th>
											<th>package name</th>
											<th>หมดอายุ</th>
											<td>สถานะ</td>
											<td>user</td>
											<th></th>
											<th></th>
										</tr>
									</thead>
									<tbody>
										<?php
										foreach($params['products'] as $key => $row){
										$date = new DateTime($row['dateTimeout']);
										$dateTimeout = $row['dateTimeout'] == '0000-00-00'? '-' : $date->format('j/n/Y');
										if($row['status']==1){
											$status = 'ปกติ';
										}
										else{
											$status = 'ระงับการใช้งาน';
										}
										$package = "<strong>{$row['package']['type']}</strong><br /><small>{$row['package']['name']}</small>";
										echo <<<HTML
											<tr class="list-row" rowId="{$row['id']}">
												<th class="row-id"><a target="_blank" href="old.php?page=product&id={$row['id']}">{$row['id']}</a></th>
												<th class="row-package">{$package}</th>
												<th class="row-dateTimeout">{$dateTimeout}</th>
												<td class="row-status">{$status}</td>
												<td class="row-account">{$row['account']['email']}</td>
												<td class="del"><button class="editButton btn btn-warning" aid={$row['id']}>แก้ไข</button></td>
												<td class="edit"><button class="delButton btn btn-danger" aid={$row['id']}>ลบ</button></td>
											</tr>
HTML;
										}?>
									</tbody>
								</table>
							</div>
						</div>
					</div>
				</div>
			</div>
		</div>
		<!--Begin Datatables-->
	</div>
</div>
<script type="text/template" class="modalAddColo">
	<div class="modal hide fade">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
			<h3>Add product colo</h3>
		</div>
		<div class="modal-body">
			<div class="alert resMessage" style="display: none;"></div>
			<form class="formProduct">
				<label>package</label>
				<select class="packageId">
					<?php foreach($params['packages'] as $key => $value){
						if($value['type'] == 'colo')
						echo <<<HTML
						<option value="{$value['id']}" data-info="{$value['info']}">{$value['type']} {$value['name']}</option>
HTML;
					}?>
				</select>
                <div class="alert alert-info package-info hide fade"></div>
				<label>ลูกค้า</label>
				<div class="account"></div>
                <input type="hidden" name="accountId" class="accountId" />
				<label>รอบชำระ (เดือน)</label>
				<input type="text" class="month input-mini" placeholder="" /><span class="help-inline"></span>
				<label>ip</label>
				<input type="hidden" class="ipId" name="ipId" />
                <label>หมายเหตุ</label>
                <textarea class="note"></textarea>
			</form>
		</div>
		<div class="modal-footer">
            <button class="btn cancel">Cancel</button>
            <button class="btn btn-primary Add">Add</button>
		</div>
	</div>
</script>

<script type="text/template" class="modalAddVPS">
	<div class="modal hide fade">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
			<h3>Add product vps</h3>
		</div>
		<div class="modal-body">
			<div class="alert resMessage" style="display: none;"></div>
			<form class="formProduct">
				<label>package</label>
				<select class="packageId">
					<?php foreach($params['packages'] as $key => $value){
						if($value['type'] == 'vps')
						echo <<<HTML
						<option value="{$value['id']}" data-info="{$value['info']}">{$value['name']}</option>
HTML;
					}?>
				</select>
                <div class="alert alert-info package-info hide fade"></div>
                <label>ลูกค้า</label>
                <div class="account"></div>
                <input type="hidden" name="accountId" class="accountId" />
                <label>รอบชำระ (เดือน)</label>
                <input type="text" class="month input-small" /><span class="help-inline"></span>
                <label>ip</label>
                <input type="hidden" class="ipId" name="ipId" />
                <label>หมายเหตุ</label>
                <textarea class="note"></textarea>

				<label>os</label>
				<select class="os">
                    <?php InvoiceVPS::instance();?>
					<option value="<?php echo InvoiceVPS::OS_LINUX;?>">linux</option>
					<option value="<?php echo InvoiceVPS::OS_WINDOW;?>">window</option>
				</select>
			</form>
		</div>
		<div class="modal-footer">
            <button class="btn cancel">Cancel</button>
            <button class="btn btn-primary Add">Add</button>
		</div>
	</div>
</script>

<script type="text/template" class="modalAddHosting">
	<div class="modal hide fade">
		<div class="modal-header">
			<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
			<h3>Add product hosting</h3>
		</div>
		<div class="modal-body">
			<div class="alert resMessage" style="display: none;"></div>
			<form class="formProduct">
				<label>package</label>
				<select class="packageId">
					<?php foreach($params['packages'] as $key => $value){
						if($value['type'] == 'hosting')
						echo <<<HTML
						<option value="{$value['id']}" data-info="{$value['info']}">{$value['name']}</option>
HTML;
					}?>
				</select>
                <div class="alert alert-info package-info hide fade"></div>
                <label>ลูกค้า</label>
                <div class="account"></div>
                <input type="hidden" name="accountId" class="accountId" />
                <label>รอบชำระ (เดือน)</label>
                <input type="text" class="month input-small" /><span class="help-inline"></span>
                <label>หมายเหตุ</label>
                <textarea class="note"></textarea>

				<label>domain</label>
				<input type="text" class="domain" value="" />
			</form>
		</div>
		<div class="modal-footer">
			<button class="btn cancel">Cancel</button>
			<button class="btn btn-primary Add">Add</button>
		</div>
	</div>
</script>
<script type="text/javascript">
$(function(){

    function initIP(modal, ips, defaultIp)
    {
        function format(item) { return item.ip; };
        var select2 = $('.ipId', modal).select2({
            placeholder: 'Search from ip',
            data: { results: ips, text: function(item){ return item.ip; } },
            formatSelection: format,
            formatResult: format
        });
        if(typeof defaultIp != 'undefined')
            select2.select2('val', defaultIp);
    }

    function initPackage(modal)
    {
        $('.packageId', modal).change(function(event){
            var packageId = $(this).val();
            var info = $('option[value="'+packageId+'"]', $(this)).attr('data-info');
            $('.package-info', modal).removeClass('hide').addClass('in').html(
                info.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + '<br />' + '$2')
            );
        });
    }

    function initAdd(modal)
    {
        $(".account", modal).select2({
            placeholder: "Search for a account",
            minimumInputLength: 3,
            ajax: {
                url: "old.php",
                dataType: 'json',
                quietMillis: 20,
                cache: true,
                data: function (term, page) { // page is the one-based page number tracked by Select2
                    return {
                        q: term, //search term
                        page_num: page,
                        page_limit: 10, // page size
                        page: 'api/account' // page number
                    };
                },
                results: function (data, page) {
                    var more = (page * 10) < data.total; // whether or not there are more results available

                    // notice we return the value of more so Select2 knows if more results can be loaded
                    return {results: data.data, more: more};
                }
            },
            formatResult: function(object, container, query){
                var html = '<span class="selectBoxOptionCode">'+object.email+'</span>';
                if(object.name!=''){
                    html += '<span>'+object.name+'</span>';
                }
                return html;
            }, // omitted for brevity, see the source of this page
            formatSelection: function(object, container){
                var html = '<span>'+object.email+'</span>';
                $('.accountId', modal).val(object.id);
                return html;
            },
            dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
            escapeMarkup: function (m) { return m; }
        });
    }

    $('.list-row').delegate('.delButton', 'click', function(event){
        if(!confirm('ยืนยันการลบ')){
            return;
        }
		var dTarget = $(event.delegateTarget);
		var id = dTarget.attr('rowId');
		$('.delButton', dTarget).button('loading');
		$.ajax('old.php?page=technic/product.rest', {
			type: 'DELETE',
			data: {id: id},
			dataType: 'JSON',
			success: function(data){
				if(data.success){
					dTarget.fadeOut('slow', function(){
						$(this).remove();
					});
				}
			}
		});
		$('.delButton', dTarget).popover('hide');
	})
	.delegate('.editButton', 'click', function(event){
		var dTarget = $(event.delegateTarget);
		var target = $(event.target);
		var id = dTarget.attr('rowId');

        function successInit(res)
        {
            target.button('reset');
            var data = res.data;
            if(typeof data.error != 'undefined'){
                alert(data.error.message);
                return;
            }

            var modal;
            var product = data.product;
            if(product.type=='colo')
                modal = $($('.modalAddColo').html());
            else if(product.type=='vps'){
                modal = $($('.modalAddVPS').html());
                $('.os', modal).val(product.os);
            }
            else if(product.type=='hosting')
                modal = $($('.modalAddHosting').html());
            modal.modal();

            $('.cancel', modal).click(function(){
                $('.close', modal).click();
            });

            var h = $('.modal-header h3', modal).text();
            $('.modal-header h3', modal).text(h.replace('Add', 'Edit'));

            $('.packageId', modal).attr('readonly', true);
            initPackage(modal);
            $('.packageId', modal).val(product.packageId).change()
                .bind('click mousedown mouseup', function(event){
                    event.preventDefault();
                    return false;
                });

            $('.month', modal).val(product.month);

            $('.note', modal).val(product.note);
            $('.note', modal).after('<label>วันหมดอายุ</label><input type="text" class="dateTimeout" name="dateTimeout" readonly />');

            var accountDiv = $('<div class="alert alert-info">');
            if($.trim(product.account.name) != '')
                accountDiv.html(product.account.name+'<br />'+product.account.email);
            else
                accountDiv.html(product.account.email);
            $('.account', modal).hide().after(accountDiv);

            $('.dateTimeout', modal).val(product.dateTimeout);
            $('.dateTimeout', modal).datepicker({ dateFormat: 'yy-mm-dd' });
            if(typeof product.ipId != 'undefined')
                initIP(modal, data.ips, product.ipId);
            if(typeof product.domain != 'undefined')
                $('.domain', modal).val(product.domain);

            $('.Add', modal).val('Edit').text('Edit').click(function(event){
                event.preventDefault();
                var button = $(event.target);

                var sub;
                if(product.type=='colo')
                    sub = {ipId: $('.ipId', modal).select2('data').id };
                else if(product.type=='vps')
                    sub = { ipId: $('.ipId', modal).select2('data').id, os: $('.os', modal).val() };
                else if(product.type=='hosting')
                    sub = { domain: $('.domain', modal).val() };

                var reqData = {
                    id: product.id,
                    type: product.type,
                    month: $('.month', modal).val(),
                    dateTimeout: $('.dateTimeout', modal).val(),
                    note: $('.note', modal).val(),
                    sub: sub
                };

                button.button('loading');
                $.ajax('old.php?page=technic/product.rest', {
                    type: 'put',
                    dataType: 'json',
                    data: reqData,
                    success: function(res){
                        button.button('reset');
                        $('.close', modal).click();
                        var dateTimeout = new Date(reqData.dateTimeout);
                        var atMonth = dateTimeout.getMonth()+1;
                        $('.row-dateTimeout', dTarget).html(dateTimeout.getDate()+'/'+atMonth+'/'+dateTimeout.getFullYear());
                    }
                });
            });
        }

		target.button('loading');
        $.ajax('old.php?page=technic/product.rest', {
            type: 'options',
            dataType: 'json',
            data: {
                operation: 'initEdit',
                id: id
            },
            success: successInit
        });
	});

	// add colo

	$('.addColoButton').click(function(event){
		event.preventDefault();
        var thisButton = $(event.target);
        thisButton.button('loading');
        $.ajax('old.php?page=technic/product.rest', {
            type: 'options',
            dataType: 'json',
            data: { operation: 'initAdd' },
            success: function(res){
                var data = res.data;
                thisButton.button('reset');
                var modal = $($('.modalAddColo').html());

                modal.modal();
                var ipIdElOri = $('.ipId', modal);

                modal.on('hidden', function(){
                    modal.remove();
                });

                initAdd(modal);
                $('.packageId', modal).change();

                initPackage(modal);
                initIP(modal, data.ips);

                $('.Add', modal).click(function(event){
                    var sendData = {
                        packageId: $('.packageId', modal).val(),
                        note: $('.note', modal).val(),
                        accountId: $('.accountId', modal).val(),
                        month: $('.month', modal).val(),
                        ipId: ipIdElOri.val()
                    };

                    $('.Add', modal).button('loading');
                    $.ajax('old.php?page=technic/product.colo.rest', {
                        dataType: 'JSON',
                        type: 'POST',
                        data: sendData,
                        success: function(data){
                            $('.Add', modal).button('reset');
                            if(typeof data.error == 'undefined'){
                                window.location.reload();
                                modal.modal('hide');
                            }
                            else {
                                alert(data.error.message);
                            }
                        }
                    });
                });

                $('.cancel', modal).click(function(){
                    $('.close', modal).click();
                });
            }
        });
	});

	// add vps
	
	$('.addVPSButton').click(function(event){
        event.preventDefault();
        var thisButton = $(event.target);
        thisButton.button('loading');
        $.ajax('old.php?page=technic/product.rest', {
            type: 'options',
            dataType: 'json',
            data: { operation: 'initAdd' },
            success: function(res){
                var data = res.data;
                thisButton.button('reset');
                var modal = $($('.modalAddVPS').html());
                modal.modal();

                var ipIdElOri = $('.ipId', modal);
                modal.on('hidden', function(){
                    modal.remove();
                });

                initAdd(modal);
                $('.packageId', modal).change();

                initPackage(modal);
                initIP(modal, data.ips);

                $('.Add', modal).click(function(event){
                    var sendData = {
                        packageId: $('.packageId', modal).val(),
                        note: $('.note', modal).val(),
                        accountId: $('.accountId', modal).val(),
                        month: $('.month', modal).val(),
                        ipId: ipIdElOri.val(),
                        os: $('.os', modal).val()
                    };
                    $('.Add', modal).button('loading');
                    $.ajax('old.php?page=technic/product.vps.rest', {
                        dataType: 'JSON',
                        type: 'POST',
                        data: sendData,
                        success: function(data){
                            $('.Add', modal).button('reset');
                            if(typeof data.error == 'undefined'){
                                window.location.reload();
                                modal.modal('hide');
                            }
                            else {
                                alert(data.error.message);
                            }
                        }
                    });
                });

                $('.cancel', modal).click(function(){
                    $('.close', modal).click();
                });
            }
        });
	});

	// add hosting
	
	$('.addHostingButton').click(function(event){
		event.preventDefault();
		var modal = $($('.modalAddHosting').html());
		
		modal.modal();
		modal.on('hidden', function(){
			modal.remove();
		});

        initAdd(modal);
        $('.packageId', modal).change();

        initPackage(modal);

		$('.Add', modal).click(function(event){
			var sendData = {
					packageId: $('.packageId', modal).val(),
					note: $('.note', modal).val(),
                    accountId: $('.accountId', modal).val(),
					month: $('.month', modal).val(),
					domain: $('.domain', modal).val()
				};
			$('.Add', modal).button('loading');
			$.ajax('old.php?page=technic/product.hosting.rest', {
				dataType: 'JSON',
				type: 'POST',
				data: sendData,
				success: function(data){
                    $('.Add', modal).button('reset');
					if(typeof data.error == 'undefined'){
                        window.location.reload();
                        modal.modal('hide');
                    }
                    else {
                        alert(data.error.message);
                    }
				}
			});
		});
		
		$('.cancel', modal).click(function(){
			$('.close', modal).click();
		});
	});

    var oTable = $('.dataTable').dataTable({"bFilter": false, "bInfo": false, "bSort": false,
        sDom: "<'pull-right'l>t<'row-fluid'<'span6'f><'span6'p>>",
        sPaginationType: "bootstrap",
        oLanguage: {
            "sLengthMenu": "Show _MENU_ entries"
        }
    });

    function delRow(row){
        $(row).fadeOut(function(){
            row = $(row).get(0);
            oTable.fnDeleteRow(oTable.fnGetPosition(row));
        });
    }
});
</script>